import { ElMessage } from 'element-plus';

let messageInstance = null;

export const _msgBox = (msg, type) => {
  if (messageInstance) {
    // 如果存在一个消息提示，先关闭
    ElMessage.closeAll();
  }
  let msgType = 'success';
  let typeList = ['success', 'warning', 'info', 'error'];
  if (type && isNaN(Number(type)) && typeList.includes(type)) {
    msgType = type;
  } else if (type && !isNaN(Number(type)) && Number(type) < typeList.length) {
    msgType = typeList[Number(type)];
  } else if (
    (type && isNaN(Number(type)) && !typeList.includes(type)) ||
    (type && !isNaN(Number(type)) && Number(type) >= typeList.length)
  ) {
    throw new Error('type参数错误');
  }

  messageInstance = ElMessage({
    message: msg,
    type: msgType,
    showClose: true,
    duration: 1500,
    onClose: () => {
      messageInstance = null; // 当消息提示关闭时，将实例置为null
    },
  });
};
